﻿using System;
using System.Web.Caching;
using System.Web;
using System.Collections;

namespace ART.Common
{
    /// <summary>
    /// 缓存操作类
    /// Create by Jinlong Zhang
    /// </summary>
    public class JCache
    {
        private static readonly Cache M_cache;

        /// <summary>
        /// 构造函数，设置当前缓存类型
        /// </summary>
        static JCache()
        {
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                M_cache = context.Cache;
            }
            else
            {
                M_cache = HttpRuntime.Cache;
            }
        }


        /// <summary>
        /// 读取指定的缓存
        /// </summary>
        /// <param name="key">键</param>
        public static object Get(string key)
        {
            return M_cache[key];
        }



        /// <summary>
        /// 加入缓存 缓存天数
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="obj">要缓存的对象</param>
        public static void Insert(string key, object obj,double days)
        {
            if (obj != null)
                M_cache.Insert(key, obj, null, DateTime.Now.AddDays(days), TimeSpan.Zero, CacheItemPriority.Normal, null);

        }

        /// <summary>
        /// 移除指定缓存
        /// </summary>
        public static void Remove(string key)
        {
            M_cache.Remove(key);
        }

        /// <summary>
        /// 移除指定缓存
        /// </summary>
        public static void Remove_Contains(string key)
        {
            IDictionaryEnumerator CacheEnum = M_cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                if (CacheEnum.Key.ToString().Contains(key))
                {
                    M_cache.Remove(CacheEnum.Key.ToString());
                }
            }
        }
        /// <summary>
        /// 清除所有数据缓存
        /// </summary>
        public static void Clear()
        {
            IDictionaryEnumerator CacheEnum = M_cache.GetEnumerator();
            while (CacheEnum.MoveNext())
                M_cache.Remove(CacheEnum.Key.ToString());

        }

        /// <summary>
        /// 清空浏览器客户端的缓存
        /// </summary>
        public static void ClearClientPageCache()
        {
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Expires = 0;
            System.Web.HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            System.Web.HttpContext.Current.Response.AddHeader("pragma", "no-cache");
            System.Web.HttpContext.Current.Response.AddHeader("cache-control", "private");
            System.Web.HttpContext.Current.Response.CacheControl = "no-cache";
        }
    }
}
